package com.xbongbong.pro.aiassistant.handle;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.aiassistant.abstracts.AbstractAiAssistantStrategyHandle;
import com.xbongbong.pro.aiassistant.service.SmartSettingsEsService;
import com.xbongbong.pro.aiassistant.service.SsDistributeSaveService;
import com.xbongbong.pro.aiassistant.service.SsMessageMergeService;
import com.xbongbong.pro.constant.AiAssistantConstant;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.domain.entity.AiAssistantHistoryEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.smartsettings.enums.AiAssistantPushTypeEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartActionTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.AiAssistantBaseProducer;
import com.xbongbong.pro.service.toolbox.smartsettings.help.SmartSettingsHelp;
import com.xbongbong.pro.smartsettings.pojo.AddOrUpdateHistoryPojo;
import com.xbongbong.pro.smartsettings.pojo.SsExecutorPojo;
import com.xbongbong.pro.smartsettings.pojo.SsExecutorUserIdPojo;
import com.xbongbong.pro.smartsettings.pojo.SsMessageMergePojo;
import com.xbongbong.pro.smartsettings.pojo.dto.RunStrategyDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartStrategyRabbitMqDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2020/09/15 16:44
 */
@Service("paasAiAssistantStrategyHandle")
public class PaasAiAssistantStrategyHandle extends AbstractAiAssistantStrategyHandle implements AiAssistantStrategyHandle {

    private static final Logger LOGGER = LoggerFactory.getLogger(PaasAiAssistantStrategyHandle.class);

    @Resource
    private SmartSettingsEsService smartSettingsEsService;
    @Resource
    private SsMessageMergeService ssMessageMergeService;
    @Resource
    private SmartSettingsHelp smartSettingsHelp;
    @Resource
    private AiAssistantBaseProducer aiAssistantBaseProducer;
    @Resource
    private SsDistributeSaveService ssDistributeSaveService;
    @Resource
    private UserModel userModel;

    @Override
    public void executionStrategy(SmartStrategyRabbitMqDTO rabbitMqDTO, RunStrategyDTO runStrategyDTO) {

        try {
            String corpid = rabbitMqDTO.getCorpid();
            AiAssistantEntity aiAssistantEntity = rabbitMqDTO.getAiAssistantEntity();
            // 获取该策略的数据id
            List<Long> dataIdList = getDataIds(rabbitMqDTO);
            if (CollectionsUtil.isEmpty(dataIdList)) {
                return;
            }
            // 查询历史记录
            List<AiAssistantHistoryEntity> historyList = getHistoryList(dataIdList, corpid, aiAssistantEntity.getId());
            // 对历史记录以及执行次数进行整理
            AddOrUpdateHistoryPojo addOrUpdateHistoryPojo = getAddOrUpdateList(historyList, dataIdList, aiAssistantEntity);
            List<AiAssistantHistoryEntity> addList = addOrUpdateHistoryPojo.getAddList();
            List<AiAssistantHistoryEntity> updateList = addOrUpdateHistoryPojo.getUpdateList();
            if (CollectionsUtil.isEmpty(addList) && CollectionsUtil.isEmpty(updateList)) {
                return;
            }
            // 获取数据，主要是为了拿负责人和创建人
            List<PaasFormDataEntityExt> dataList = smartSettingsEsService.getPaasDataList(corpid, SaasMarkEnum.PAAS.getCode(), dataIdList);
            // 获取执行人，拼装执行人（将部门，角色，人员，负责人，协同人，对应级主管）
            List<SsExecutorPojo> ssExecutorList = getExecutorUserList(aiAssistantEntity, dataIdList, dataList);
            // 聚合
            List<SsMessageMergePojo>  ssMessageMergeList = ssMessageMergeService.getMessageMergeList(ssExecutorList, aiAssistantEntity, addList, updateList);
            SmartActionTypeEnum smartActionTypeEnum = SmartActionTypeEnum.getByCode(aiAssistantEntity.getAction());
            switch (smartActionTypeEnum) {
                case MESSAGE:
                    sendDingTalkMessage(aiAssistantEntity, ssMessageMergeList, addList, updateList, dataList, runStrategyDTO);
                    break;
                case SMS:
                    // TODO 短信
                default:
                    break;
            }
        } catch (Exception e) {
            LOGGER.error("PaasAiAssistantStrategyHandle.executionStrategy执行出错", e);
        }
    }

    /**
     * 发送推送，并且入库
     * @param aiAssistantEntity
     * @param messageMergeList
     * @param addList
     * @param updateList
     */
    @Override
    public void sendDingTalkMessage(AiAssistantEntity aiAssistantEntity, List<SsMessageMergePojo>  messageMergeList, List<AiAssistantHistoryEntity> addList,
                                    List<AiAssistantHistoryEntity> updateList, List<PaasFormDataEntityExt> dataList, RunStrategyDTO runStrategyDTO) {
        // title内容
        String title = XbbRefTypeEnum.AI_ASSISTANT.getName() + PaasConstant.COLON + aiAssistantEntity.getName();
        String corpid = aiAssistantEntity.getCorpid();
        // 发送时间
        String sendTimeStr = getStrategyTime(aiAssistantEntity);
        // 产品库存预警、四个待跳转用到pushType
        AiAssistantPushTypeEnum pushTypeEnum = smartSettingsHelp.otherPush(aiAssistantEntity);
        Long sendTime = DateTimeUtil.getInt(sendTimeStr, DateTimeUtil.SDFYMDHM);
        // 其他消息
        for (SsMessageMergePojo item : messageMergeList) {

            if (item.getDataIdList().size() > AiAssistantConstant.MAX_DATAID_LENGTH) {
                // 记录数据
                continue;
            }

            // 占位符替换
            String content = ssDistributeSaveService.handleContentPlaceholder(aiAssistantEntity.getMemo(), "", item.getDataIdList().size(), "");

            PushRefTypePojo.Options options = new PushRefTypePojo.Options(aiAssistantEntity.getAppId(), aiAssistantEntity.getMenuId(),
                    aiAssistantEntity.getFormId(), null, item.getDataIdList(), aiAssistantEntity.getSaasMark(),
                    aiAssistantEntity.getBusinessType(), aiAssistantEntity.getBusinessType());

            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(item.getExcutorId()), item.getDataIdList(), 0,
                    sendTime, title, content, null, options);

            // 四个待推送有类型
            if (Objects.isNull(pushTypeEnum)) {
                if (Objects.equals(aiAssistantEntity.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                    pushTypeEnum = AiAssistantPushTypeEnum.getPushTypeBySubCode(aiAssistantEntity.getBusinessType());
                } else {
                    pushTypeEnum = AiAssistantPushTypeEnum.PAAS_PUSH;
                }
            } else {

            }
            if (Objects.equals(AiAssistantPushTypeEnum.UNKNOWN, pushTypeEnum)) {
                return;
            }
            try {
                // 分发数据
                aiAssistantBaseProducer.sendMessage(pushTypeEnum, messageRabbitMqDTO);

            } catch (Exception e) {
                LOGGER.error("PaasAiAssistantStrategyHandle.sendMessage 发送失败", e);
            }
        }
        // 入库
        messageDataSave(corpid, addList, updateList);
    }


    /**
     * 获取执行人
     * @param aiAssistantEntity 智能助手
     * @param dataIdList 数据id列表
     * @param formDataList 数据
     * @return
     */
    @Override
    public List<SsExecutorPojo> getExecutorUserList(AiAssistantEntity aiAssistantEntity, List<Long> dataIdList, List<PaasFormDataEntityExt> formDataList) {
        String corpid = aiAssistantEntity.getCorpid();
        List<SsExecutorPojo> ssExecutorList = new ArrayList<>();
        // // 当前需要执行的人员
        SsExecutorUserIdPojo ssExecutorUserIdPojo = getExecUserIds(aiAssistantEntity);
        Set<String> execUserIds = ssExecutorUserIdPojo.getExecUserIds();
        // 负责人
        Set<Integer> managerLevels = ssExecutorUserIdPojo.getManagerLevels();


        // TODO 协同人还没实现，tb_paas_co_user
        Long aiAssistantId = aiAssistantEntity.getId();
        Long formId = aiAssistantEntity.getFormId();
        if (Objects.nonNull(dataIdList)) {
            for (PaasFormDataEntityExt entityExt : formDataList) {
                Long dataId = entityExt.getId();
                // 负责人
                if (StringUtil.isNotEmpty(entityExt.getOwnerId()) && !managerLevels.isEmpty()) {
                    execUserIds.add(entityExt.getOwnerId());
                }
                // TODO 协同人
                // 执行人实体
                List<UserEntity> execUserList = userModel.getByUserIdIn(corpid, execUserIds, true);
                // 拼接执行人数据
                SsExecutorPojo pojo = new SsExecutorPojo(aiAssistantId, formId, dataId, new ArrayList<>(execUserIds), execUserList);
                ssExecutorList.add(pojo);
            }
        }
        return ssExecutorList;
    }

}
